package com.ai.web.weixin.processor;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.web.cache.Constants;
import com.ai.web.service.WxRoleService;
import com.ai.web.service.WxUserService;
import com.ai.web.vo.WxRoleV;
import com.ai.web.vo.WxUserV;
import com.ai.web.weixin.message.request.ReqBaseMessage;
import com.ai.web.weixin.message.response.TextMessage;
import com.ai.web.weixin.message.util.MessageUtil;
import com.tiny.persistence.domain.WxRole;
import com.tiny.persistence.domain.WxUser;

@Service(value = "followMsgProcessor")
public class FollowMsgProcessor implements IMessageProcessor {

	private static Logger logger = Logger.getLogger(FollowMsgProcessor.class);

	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private WxRoleService wxRoleService;

	public String process(ReqBaseMessage bm) {

		logger.info("[Follow Processor] " + bm.toString());
		WxUser user = wxUserService.getByOpenId(bm.getFromUserName());
		if (user == null) {
			WxUserV wxUser = new WxUserV();
			wxUser.setOpenId(bm.getFromUserName());
			WxRole wxRole = new WxRole();
			try {
				WxRoleV role = wxRoleService.getRole(Constants.WX_DEFAULT_ROLE);
				BeanUtils.copyProperties(role, wxRole);
				wxUser.setWxRole(wxRole);
				wxUser.setIsPassed(0);
				wxUser.setCreateTime(new Date());
				wxUserService.saveWxUser(wxUser);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 关注时回复
		String content = "您好！感谢您关注中智融通官方微信，本平台将为您提供产品信息、交流、"
				+ "活动、保修、培训、预约等服务。我们的服务时间为9:00~21:00,部分功能为会员专用,<a href=\"#\">请回复\"姓名"
				+ "#手机号码#公司名称\"</a>进行会员验证获得更高权限, 谢谢合作。";

		// 回复文本消息
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(bm.getFromUserName());
		textMessage.setFromUserName(bm.getToUserName());
		textMessage.setCreateTime(System.currentTimeMillis());
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setContent(content);
		return MessageUtil.textMessageToXml(textMessage);
	}

}
